package com.hengxinguotong.zhihuichengjian.ui;

import android.Manifest;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.HomeTabAdapter;
import com.hengxinguotong.zhihuichengjian.bean.HomeTab;
import com.hengxinguotong.zhihuichengjian.bean.MenuBean;
import com.hengxinguotong.zhihuichengjian.bean.MenuListRes;
import com.hengxinguotong.zhihuichengjian.bean.VersionInfo;
import com.hengxinguotong.zhihuichengjian.dialog.AppUpgradeDialog;
import com.hengxinguotong.zhihuichengjian.fragment.BuildMenuFragment;
import com.hengxinguotong.zhihuichengjian.fragment.GovernmentHomeFragment;
import com.hengxinguotong.zhihuichengjian.fragment.HomeFragment;
import com.hengxinguotong.zhihuichengjian.fragment.MapFragment;
import com.hengxinguotong.zhihuichengjian.fragment.MyFragment;
import com.hengxinguotong.zhihuichengjian.fragment.NewsFragment;
import com.hengxinguotong.zhihuichengjian.ui.app.BaseFragment;
import com.hengxinguotong.zhihuichengjian.utils.ActivityController;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.view.CustomPatient;
import com.pgyersdk.javabean.AppBean;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.functions.Consumer;

/**
 * 主页面
 */
public class MainActivity extends BaseActivity implements HomeTabAdapter.OnClickListener
{
    public static final String HOME = "首页";
    public static final String BUILD = "建设管理";
    public static final String NEWS = "资讯";
    public static final String MY = "我的";
    @BindView(R.id.main_root_fragment)
    FrameLayout mainRootFragment;
    @BindView(R.id.tab_rv)
    RecyclerView tabRv;

    private String vedio_ip, vedio_username, vedio_password;
    private int vedio_port;
    private int level;
    private HomeTabAdapter tabAdapter;
    private List<HomeTab> tabList;
    private List<BaseFragment> fragmentList;
    private FragmentManager fragmentManager = null;
    private FragmentTransaction fragmentTransaction = null;

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState)
    {
//        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        level = SPUtil.getInt(this, "level");
        initFragment();
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
//        {
//            if (!Utils.hasPermission(this, Manifest.permission.CAMERA))
//            {
//                requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
//            }
//            if (!Utils.hasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE))
//            {
//                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
//            }
//            if (!Utils.hasPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE))
//            {
//                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 6);
//            }
//            if (!Utils.hasPermission(this, Manifest.permission.SYSTEM_ALERT_WINDOW))
//            {
//                requestPermissions(new String[]{Manifest.permission.SYSTEM_ALERT_WINDOW}, 3);
//            }
//            if (!Utils.hasPermission(this, Manifest.permission.VIBRATE))
//            {
//                requestPermissions(new String[]{Manifest.permission.VIBRATE}, 4);
//            }
//            if (!Utils.hasPermission(this, Manifest.permission.INTERNET))
//            {
//                requestPermissions(new String[]{Manifest.permission.INTERNET}, 5);
//            }
//        }
        RxPermissions rxPermissions = new RxPermissions(MainActivity.this);
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA
                ,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION)
                .subscribe(new Consumer<Boolean>()
                {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception
                    {
                        if (aBoolean)
                        {
                            initVersion();
                        } else
                        {
                            showToast("权限被禁止，部分功能可能受限");
                        }
                    }
                });
        pgyerVersionUpdate();
    }

    private void initFragment()
    {
        fragmentList = new ArrayList<>();
        fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        tabList = new ArrayList<>();

        BaseFragment homeFragment = null;
        switch (level)
        {
            case 1:
            case 2:
                homeFragment = new GovernmentHomeFragment();
                break;
            case 3:
                homeFragment = new HomeFragment();
                break;
            case 0:
//                homeFragment = new EnterpriseFragment();
                homeFragment = new MapFragment();
                break;
        }
        fragmentTransaction.add(R.id.main_root_fragment, homeFragment, HOME);
        fragmentList.add(homeFragment);
        tabList.add(new HomeTab(R.drawable.icon_tab_home, HOME, true));

        if (level == 0)
        {
            String authority = SPUtil.getString(this, "authority");
            if (!Utils.isEmpty(authority))
            {
                MenuListRes menuListRes = new Gson().fromJson(authority, MenuListRes.class);
                if (menuListRes.getValue() != null && menuListRes.getValue().size() > 0)
                {
                    for (MenuBean menu : menuListRes.getValue())
                    {
                        if (menu.getId() == 1500)
                        {
                            BuildMenuFragment buildMenuFragment = new BuildMenuFragment();
                            fragmentTransaction.add(R.id.main_root_fragment, buildMenuFragment, BUILD);
                            fragmentTransaction.hide(buildMenuFragment);
                            fragmentList.add(buildMenuFragment);
                            tabList.add(new HomeTab(R.drawable.icon_tab_build, BUILD, false));
                        }
                    }
                }
            }
        }

        BaseFragment newsFragment = new NewsFragment();
        fragmentTransaction.add(R.id.main_root_fragment, newsFragment, NEWS);
        fragmentTransaction.hide(newsFragment);
        fragmentList.add(newsFragment);
        tabList.add(new HomeTab(R.drawable.icon_tab_news, NEWS, false));

        BaseFragment myFragment = new MyFragment();
        fragmentTransaction.add(R.id.main_root_fragment, myFragment, MY);
        fragmentTransaction.hide(myFragment);
        fragmentList.add(myFragment);
        tabList.add(new HomeTab(R.drawable.icon_tab_my, MY, false));
        fragmentTransaction.commit();

        tabAdapter = new HomeTabAdapter(this, tabList);
        tabAdapter.setOnClickListener(this);
        tabRv.setAdapter(tabAdapter);
        tabRv.setItemAnimator(new DefaultItemAnimator());
        tabRv.setLayoutManager(new GridLayoutManager(this, tabList.size()));
    }

    public String gethJson()
    {
        return hJson;
    }

    private String hJson;

    public void setNotRead(int type)
    {
        exchangePage(0);
        BaseFragment fragment = fragmentList.get(0);
        if (fragment instanceof HomeFragment)
        {
            ((HomeFragment) fragment).updateMenu(type);
        }
    }

    //获取海康的用户和iP
//    private void initVideoUser(String uuid, final String areaId) {
//        RequestParams params = new RequestParams();
//        params.addBodyParameter("areaId", "1905");
//        Utils.requestData(null, this, "/video/queryHikLoginInfoByArea/" + uuid, params, new Utils.ListenerJson() {
//            @Override
//            public void onSuccess(String json) {
//                if (json != null) {
//                    HKRes hkRes = new Gson().fromJson(json, HKRes.class);
//                    if (hkRes.getStatus() == 1) {
//                        login(hkRes.getValue().getIp(), hkRes.getValue().getUsername(), hkRes.getValue().getPassword());
//                    }
//                }
//            }
//            @Override
//            public void onFailure(String json) {
////                changeFragment(new HomeFragment(), null);
//            }
//        });
//    }

    private long currentTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit()
    {
        if ((System.currentTimeMillis() - currentTime) > 2000)
        {
            Toast.makeText(getApplicationContext(), "再次点击退出", Toast.LENGTH_SHORT).show();
            currentTime = System.currentTimeMillis();
        } else
        {
            if (FloatSwitchActivity.floatService != null)
            {
                stopService(FloatSwitchActivity.floatService);
                FloatSwitchActivity.floatService = null;
                SPUtil.put(this, "service", 0);
            }
            ActivityController.finishAll();
            System.exit(0);
        }
    }

    //提示对话框
    private void showDialog()
    {
        Typeface lantypeFace = Utils.getTypeface(this);
        Typeface typeFace = Utils.getTypeface(this);
        CustomPatient.Builder builder = new CustomPatient.Builder(this);
        builder.setContent("退出登录", lantypeFace, typeFace);
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
                //设置你的操作事项
            }
        });
        builder.setNegativeButton("确定",
                new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int which)
                    {
                        dialog.dismiss();
                        Utils.loginOut(MainActivity.this);
                        Toast.makeText(MainActivity.this, "退出成功", Toast.LENGTH_SHORT).show();
                    }
                });

        CustomPatient CustomPatient = builder.create();
        CustomPatient.show();
        Window window = CustomPatient.getWindow();
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值
        p.height = (int) (d.getHeight() * 0.20); // 宽度设置为屏幕的0.20
        p.width = (int) (d.getWidth() * 0.70); // 宽度设置为屏幕的0.65
        window.setAttributes(p);
    }

    /*
    蒲公英版本更新
     */
    private void pgyerVersionUpdate()
    {
        PgyUpdateManager.register(this, "com.hengxinguotong.zhihuigongdi.provider_paths", new UpdateManagerListener()
        {
            @Override
            public void onNoUpdateAvailable()
            {

            }

            @Override
            public void onUpdateAvailable(String result)
            {
                // 将新版本信息封装到AppBean中
                final AppBean appBean = getAppBeanFromString(result);
                CustomPatient.Builder builder = new CustomPatient.Builder(MainActivity.this);
                Typeface lantypeFace = Utils.getTypeface(MainActivity.this);
                Typeface typeFace = Utils.getTypeface(MainActivity.this);
                builder.setTitle("更新");
                builder.setContent("发现新版本，是否更新？", lantypeFace, typeFace);
                builder.setPositiveButton("确定",
                        new DialogInterface.OnClickListener()
                        {

                            @Override
                            public void onClick(
                                    DialogInterface dialog,
                                    int which)
                            {
                                startDownloadTask(
                                        MainActivity.this,
                                        appBean.getDownloadURL());
                            }
                        });
                builder.setNegativeButton(
                        "取消", new DialogInterface.OnClickListener()
                        {

                            @Override
                            public void onClick(DialogInterface dialog, int which)
                            {
                                dialog.dismiss();
                            }
                        });
                CustomPatient CustomPatient = builder.create();
                CustomPatient.show();
                Window window = CustomPatient.getWindow();
                WindowManager m = getWindowManager();
                Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
                WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值
                p.height = (int) (d.getHeight() * 0.23); // 改变的是dialog框在屏幕中的位置而不是大小
                p.width = (int) (d.getWidth() * 0.85); // 宽度设置为屏幕的0.65
                window.setAttributes(p);
            }
        });
    }

    /*
    检查版本更新
     */
    private void initVersion()
    {
        Utils.requestData("检测版本中…", this, "/versionUpdate/query/" + SPUtil.getString(this, "uuid"), null, new Utils.ListenerJson()
        {
            @Override
            public void onSuccess(String json)
            {
                if (!Utils.isEmpty(json))
                {
                    VersionInfo versionInfo = new Gson().fromJson(json, VersionInfo.class);
                    if (1 == versionInfo.status)
                    {//接口调用标识.1:成功; 0:失败。
                        processVersion(versionInfo);
                    } else
                    {
                        showToast("版本检测失败，请稍后重试。");
                    }
                }
            }

            @Override
            public void onFailure(String json)
            {
                showToast("版本检测失败，请稍后重试。");
            }
        });
    }

    private void processVersion(VersionInfo versionInfo)
    {
        int newVersionCode = versionInfo.value.versionNo;
//        String versionName = Utils.getVersionName(mainActivity);
//        double currentVersion = Double.parseDouble(versionName);
        int currentVersionCode = Utils.getVersionCode(this);

        //判断当前的版本
        if (newVersionCode > currentVersionCode)
        {
            SPUtil.put(MainActivity.this, "hasNewVersion", true);
            final String filePath = versionInfo.value.filePath;
            SPUtil.put(MainActivity.this, "apkPath", filePath);
            //提醒更新
            CustomPatient.Builder builder = new CustomPatient.Builder(this);
            Typeface lantypeFace = Utils.getTypeface(this);
            Typeface typeFace = Utils.getTypeface(this);
            builder.setTitle("版本更新");
            builder.setContent("检测到新版本，立即更新吗？", lantypeFace, typeFace);
            builder.setPositiveButton("稍后更新", new DialogInterface.OnClickListener()
            {
                public void onClick(DialogInterface dialog, int which)
                {
                    dialog.dismiss();

                }
            });

            builder.setNegativeButton("立即更新",
                    new DialogInterface.OnClickListener()
                    {
                        public void onClick(DialogInterface dialog, int which)
                        {
                            dialog.dismiss();
//                            Utils.downFile(filePath, MainActivity.this);
                            AppUpgradeDialog appUpgradeDialog = new AppUpgradeDialog(MainActivity.this);
                            appUpgradeDialog.setDownloadPath(filePath);
                            appUpgradeDialog.show();
                        }
                    });
            CustomPatient CustomPatient = builder.create();
            CustomPatient.show();
            Window window = CustomPatient.getWindow();
            WindowManager m = getWindowManager();
            Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
            WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值
            p.height = (int) (d.getHeight() * 0.23); // 改变的是dialog框在屏幕中的位置而不是大小
            p.width = (int) (d.getWidth() * 0.85); // 宽度设置为屏幕的0.65
            window.setAttributes(p);
        } else
        {
            SPUtil.put(this, "hasNewVersion", false);
        }
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        JPushInterface.onResume(getApplicationContext());
    }

    @Override
    protected void onPause()
    {

        super.onPause();
        JPushInterface.onPause(getApplicationContext());
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        PgyUpdateManager.unregister();
    }

    @Override
    public void onClick(Object o)
    {
        HomeTab tab = (HomeTab) o;
        if (tab == null)
        {
            return;
        }
        if (level == 0)
        {
            switch (tab.getName())
            {
                case HOME:
                    exchangePage(0);
                    break;
                case BUILD:
                    exchangePage(1);
                    break;
                case NEWS:
                    exchangePage(fragmentList.size() == 3 ? 1 : 2);
                    break;
                case MY:
                    exchangePage(fragmentList.size() == 3 ? 2 : 3);
                    break;
            }
        } else
        {
            switch (tab.getName())
            {
                case HOME:
                    exchangePage(0);
                    break;
                case NEWS:
                    exchangePage(1);
                    break;
                case MY:
                    exchangePage(2);
                    break;
            }
        }
    }

    private void exchangePage(int index)
    {
        fragmentTransaction = fragmentManager.beginTransaction();
        BaseFragment fragment;
        HomeTab tab;
        for (int i = 0; i < fragmentList.size(); i++)
        {
            fragment = fragmentList.get(i);
            tab = tabList.get(i);
            if (i == index)
            {
                tab.setChecked(true);
                fragmentTransaction.show(fragment);
            } else
            {
                tab.setChecked(false);
                fragmentTransaction.hide(fragment);
            }
        }
        fragmentTransaction.commitAllowingStateLoss();
        tabAdapter.setDataList(tabList);
    }
}
